package com.ck.print.demo.printbridge;

import org.apache.commons.lang3.StringUtils;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
import java.util.stream.Collectors;

public class MacAddressUtil {

    private static String AgentMac;

    /**
     * 获取代理的mac 地址
     * @return
     */
    public static String agentMac() {
        if (StringUtils.isBlank(AgentMac)) {
            synchronized (MacAddressUtil.class) {
                if (StringUtils.isBlank(AgentMac)) {
                    List<String> macAddresses = MacAddressUtil.findMacAddresses(Collections.singletonList("Virtual"));
                    AgentMac = String.join(",", macAddresses);
                }
            }
        }
        return AgentMac;
    }


    public static List<String> findMacAddresses(List< String> filterName) {
        List<String> macAddresses = new ArrayList<>();
        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();

                // 过滤回环接口和未启用的接口
                if (ni.isLoopback() || !ni.isUp()) {
                    continue;
                }

                // 获取MAC地址（硬件地址）
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    // 转换为十六进制字符串
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }

                    // 输出接口名称和对应的MAC地址
                    if (filterName.stream().anyMatch(name -> StringUtils.containsIgnoreCase(ni.getDisplayName(), name))){
                        continue;
                    } else {
                        macAddresses.add(sb.toString());
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        return macAddresses.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());
    }

//    public static void main(String[] args) {
//        List<String> macAddresses = findMacAddresses(List.of("Virtual"));
//        macAddresses.forEach(System.out::println);
//    }
}
